import { ReactElement, useRef, useEffect, useState, RefObject } from 'react'
import { Modal, Form, Input, FormInstance, message, AutoComplete, Spin, Empty } from 'antd'
import { DataSchema } from '../../ajax'
import UnitNumberInput from '@components/unitNumberInput'
import { WorkPerformanceSchema } from '@src/components/schema/performanceSchema'
import { awaitWrap } from '@js/tool'
import { addRequest, updateRequest, getCaseListRquesst } from './ajax'
import { CaseSchema } from '@src/components/schema/caseSchema'
import style from './index.module.less'

const { Item } = Form
const { TextArea } = Input

async function submitHandle (d: { [k: string]: any }, work: WorkPerformanceSchema | null, performanceid: string, hide: () => void, refreshData: () => void): Promise<void> {
  if (work === null) {
    return undefined
  }
  const id: string = d.id
  let fn = addRequest
  if (typeof id !== 'string') {
    d.performanceid = performanceid
    d.accountid = work.accountid
    d.name = work.name
  } else {
    fn = updateRequest
  }
  const h = message.loading('提交中')
  const [e] = await awaitWrap(fn(d))
  h()
  if (e === null) {
    message.success(typeof id === 'string' ? '更新成功' : '添加成功').then(null, null)
    hide()
    refreshData()
  }
}

// 获取案件列表
async function getCaseList (str: string, setList: (v: CaseSchema[]) => void, setLoading: (v: boolean) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseListRquesst(str))
  setLoading(false)
  if (e === null && d instanceof Array) {
    setList(d)
  }
}

// 渲染空结果
function EmptyContent (loading: boolean): ReactElement {
  if (loading) {
    return <div className={style.loading}><Spin /></div>
  }
  return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
}

function changeCaseno (v: string, caseList: CaseSchema[], formRef: RefObject<FormInstance>): void {
  for (let i = 0; i < caseList.length; i++) {
    const o = caseList[i]
    if (o.caseno_desc === v) {
      formRef.current?.setFieldsValue({ caseid: o.id })
      break
    }
  }
}

interface Props {
  visible: boolean
  work: WorkPerformanceSchema | null
  performanceid: string
  data: DataSchema | null
  hide: () => void
  refreshData: () => void
}

function Main ({ visible, data, work, performanceid, hide, refreshData }: Props): ReactElement {
  const formRef = useRef<FormInstance>(null)
  const [caseList, setCaseList] = useState<CaseSchema[]>([])
  const [options, setOptions] = useState<Array<{ value: string }>>([])
  const [loading, setLoading] = useState(false)
  useEffect(() => {
    setOptions(caseList.map(li => ({ value: li.caseno_desc })))
  }, [caseList])
  useEffect(() => {
    const c = formRef.current
    if (data !== null && c !== null && visible) {
      c.setFieldsValue(data)
    } else if (c !== null && !visible) {
      c.resetFields()
      setCaseList([])
    }
  }, [data, formRef, visible])
  return (
    <Modal title={data === null ? '添加案件' : '修改案件'} visible={visible} maskClosable={false} onCancel={hide} onOk={() => formRef.current?.submit()}>
      <Form ref={formRef} labelCol={{ flex: '80px' }} initialValues={{ score: -5 }} onFinish={async d => await submitHandle(d, work, performanceid, hide, refreshData)}>
        <Item noStyle name='id'><span /></Item>
        <Item noStyle name='performanceid'><span /></Item>
        <Item noStyle name='caseid'><span /></Item>
        <Item noStyle name='accountid'><span /></Item>
        <Item label='案号' name='caseno_desc' rules={[{ required: true, message: '案号不能为空' }]}>
          <AutoComplete placeholder='请输入案号' options={options} onSearch={async (v: string) => { await getCaseList(v, setCaseList, setLoading) }} notFoundContent={EmptyContent(loading)} onSelect={(v: string) => changeCaseno(v, caseList, formRef)} />
        </Item>
        <Item label='描述' name='remark'>
          <TextArea placeholder='请输入' autoSize={{ minRows: 3 }}></TextArea>
        </Item>
        <Item label='扣分' name='score' rules={[{ required: true, message: '扣分不能为空' }]}>
          <UnitNumberInput precision={2} max={0} unit='分' />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
